package com.hp.springbootwebflux.exception;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.util.HashMap;

/**
 * 异常处理切面
 *
 * @author dongxing
 **/
@ControllerAdvice
public class CheckAdvice {


    @ExceptionHandler(WebExchangeBindException.class)
    public ResponseEntity handleBindException(WebExchangeBindException e) {
        return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    /**
     * 将效验异常转换为字符串
     *
     * @param e
     * @return
     */
    private String toStr(WebExchangeBindException e) {
//      return  e.getFieldErrors().stream().map(m -> m.getField() + " : " + m.getDefaultMessage()).reduce("", (s1, s2) -> s1 + "\n" + s2);
        HashMap<Object, Object> hashMaps = e.getFieldErrors().stream().collect(HashMap::new, (m, v) -> m.put(v.getField(), v.getDefaultMessage()), HashMap::putAll);
        return JSON.toJSONString(hashMaps);
    }


    @ExceptionHandler(CheckException.class)
    public ResponseEntity handleBindException(CheckException e) {
        return new ResponseEntity<String>(toStr(e), HttpStatus.BAD_REQUEST);
    }

    private String toStr(CheckException e) {
        return e.getFieldName() + ": 错误的值" + e.getFieldValue();
    }

}
